<template>
  <div class="authority">
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true">
        <el-form-item label="名称">
          <el-input v-model="searchInfo.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="渔场">
          <el-select v-model.number="searchInfo.groundsId" placeholder="请选择">
            <el-option v-for="item in fishList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">
            查询
          </el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box unit">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addUnit">新增</el-button>
      </div>
      <el-table :data="tableData" row-key="id">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column align="left" label="名称" prop="name"></el-table-column>
        <el-table-column align="left" label="开放时间" prop="openTime"></el-table-column>
        <el-table-column align="left" label="收费金额" prop="feeRuleAmount"></el-table-column>
        <el-table-column align="left" label="收费类型">
          <template #default="scope">
            <span>{{ scope.row.feeRuleUnit == 1 ? '按斤' : '按小时' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="状态" width="160">
          <template #default="scope">
            <el-switch v-model="scope.row.openStatus" size="large" :active-value="1" :inactive-value="2"
              active-text="启用" inactive-text="禁用" @change="(e) => statusChange(scope.row.id, e)" />
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" min-width="160">
          <template #default="scope">
            <el-button type="primary" link icon="edit" @click="editUnit(scope.row)">
              编辑
            </el-button>
            <el-button type="primary" link @click="openDiaoWei(scope.row)">
              钓位
            </el-button>
            <el-button type="danger" link icon="delete" @click="delUnit(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total" layout="prev, pager, next"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-drawer v-model="dialogFormVisible" :size="appStore.drawerSize" :before-close="handleClose" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ dialogTitle }}</span>
          <div>
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="enterDialog">确定</el-button>
          </div>
        </div>
      </template>
      <el-form v-if="dialogFormVisible" ref="yyglForm" label-width="150" :model="form" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入" style="width: 500px;" />
        </el-form-item>
        <el-form-item label="收费金额" prop="feeRuleAmount">
          <el-input v-model.number="form.feeRuleAmount" placeholder="请输入" style="width: 500px;" />
        </el-form-item>
        <el-form-item label="收费类型" prop="feeRuleUnit">
          <el-radio-group v-model="form.feeRuleUnit" class="ml-4" style="width: 500px;">
            <el-radio :value="1" size="large">斤</el-radio>
            <el-radio :value="2" size="large">小时</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="渔场" prop="groundId">
          <el-select v-model.number="form.groundId" placeholder="请选择" style="width: 500px;">
            <el-option v-for="item in fishList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="管理员" prop="managerId">
          <el-select v-model="form.managerId" placeholder="请选择" style="width: 500px;">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="开放时间" prop="time" style="width: 650px;">
          <el-time-picker v-model="form.time" is-range range-separator="-" start-placeholder="开始时间"
            end-placeholder="结束时间" format="HH:mm" value-format="HH:mm" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入" style="width: 500px;" />
          <el-button type="primary" style="margin-left: 6px;" @click="openMap">选择</el-button>
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入" style="width: 500px;" />
        </el-form-item>
        <el-form-item label="备注" prop="profile">
          <el-input v-model="form.profile" type="textarea" :rows="6" style="width: 500px;" />
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 位置信息 -->
    <el-drawer v-model="weizhiDialog" :size="1200" :before-close="handleClose6" :show-close="false"
      class="loudong-drawer">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">地图定位</span>
          <div>
            <el-button @click="closeDialog6">取消</el-button>
          </div>
        </div>
      </template>
      <div id="container"></div>
    </el-drawer>
    <!-- 鱼池钓位列表 -->
    <el-drawer v-model="diaoweiDialog" :size="appStore.drawerSize" :before-close="handleClose2" :show-close="false"
      class="loudong-drawer">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">鱼池钓位</span>
          <div>
            <el-button @click="diaoweiDialog = false">取消</el-button>
            <el-button type="primary" @click="addDiaoWei">新增</el-button>
          </div>
        </div>
      </template>
      <el-table :data="diaoweiData" row-key="id">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column align="left" label="钓位编号" prop="no" show-overflow-tooltip></el-table-column>
        <el-table-column align="left" label="使用状态">
          <template #default="scope">
            <span>{{ getStatus(scope.row.useStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" min-width="100">
          <template #default="scope">
            <el-button type="primary" link icon="edit" @click="changeStatus(scope.row)">
              修改状态
            </el-button>
            <el-button type="danger" link icon="delete" @click="delDw(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
    <el-drawer v-model="dwVisible" :size="appStore.drawerSize" :before-close="handleClose3" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ dialogTitle2 }}</span>
          <div>
            <el-button @click="closeDialog2">取消</el-button>
            <el-button type="primary" @click="enterDialog2">确定</el-button>
          </div>
        </div>
      </template>
      <el-form v-if="dwVisible" ref="dwForms" label-width="150" :model="dwForm" :rules="dwRules">
        <el-form-item label="钓位编号" prop="no">
          <el-input v-model="dwForm.no" placeholder="请输入" style="width: 500px;" />
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-drawer v-model="statusVisible" :size="appStore.drawerSize" :before-close="handleClose4" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">更改钓位使用状态</span>
          <div>
            <el-button @click="statusVisible = false">取消</el-button>
            <el-button type="primary" @click="enterDialog4">确定</el-button>
          </div>
        </div>
      </template>
      <el-form v-if="statusVisible" ref="statusForms" label-width="150" :model="statusForm" :rules="statusRules">
        <el-form-item label="状态" prop="useStatus">
          <el-radio-group v-model="statusForm.useStatus" class="ml-4" style="width: 500px;">
            <el-radio :value="1" size="large">空闲</el-radio>
            <el-radio :value="2" size="large">使用中</el-radio>
            <el-radio :value="3" size="large">维修中</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>
<script setup>
import {
  fishPondList,
  pondChangeStatus,
  pondDelete,
  pondAdd,
  pondedit,
  fishGroundsList,
  fishSpotList,
  fishSpotAdd,
  spotChangeStatus,
  fishSpotDelete
} from '@/api/diaochangguanli'
import {
  getAuthorityList
} from '@/api/authority'
import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import { sortBySort } from '@/utils/format'
import AMapLoader from '@amap/amap-jsapi-loader'; //引入
// 通过该函数，可以获取组件当前所在的表单项formItem
const { formItem } = useFormItem()

defineOptions({
  name: 'Yygl'
})
const appStore = useAppStore()
const form = ref({
  name: '',
  openTime: '',
  time: [],
  feeRuleAmount: '',
  feeRuleUnit: 1,
  groundId: '',
  pointsRule: '',
  profile: '',
  longitude: '',
  latitude: '',
  managerId: ''
})

const searchInfo = ref({
  name: '',
  groundsId: ''
})

const userStore = useUserStore()

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)

const rules = reactive({
  name: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
  feeRuleAmount: [{ required: true, message: '请输入收费金额', trigger: 'blur' }],
  feeRuleUnit: [{ required: true, message: '请选择收费类型', trigger: 'change' }],
  groundId: [{ required: true, message: '请选择渔场', trigger: 'change' }],
  managerId: [{ required: true, message: '请选择管理员', trigger: 'change' }],
  time: [{ required: true, message: '请选择开放时间', trigger: 'change' }],
  longitude: [{ required: true, message: '请选择经纬度', trigger: 'change' }],
  latitude: [{ required: true, message: '请选择经纬度', trigger: 'change' }],
})
const dwRules = reactive({
  no: [{ required: true, message: '请输入钓位编号', trigger: 'blur' }]
})
const statusRules = reactive({
  useStatus: [{ required: true, message: '请选择钓位使用状态', trigger: 'blur' }]
})
const yyglForm = ref(null)

const initForm = () => {
  yyglForm.value.resetFields()
  form.value = {
    name: '',
    openTime: '',
    time: [],
    feeRuleAmount: '',
    feeRuleUnit: 1,
    groundId: '',
    pointsRule: '',
    profile: '',
    longitude: '',
    latitude: '',
    managerId: ''
  }
}

const isEdit = ref(false)
const dialogTitle = ref('新增')
const addUnit = () => {
  dialogTitle.value = '新增'
  isEdit.value = false
  dialogFormVisible.value = true
}
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}
const closeDialog6 = () => {
  weizhiDialog.value = false
}
const handleClose = (done) => {
  initForm()
  done()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
  const res = await fishPondList({
    pageNumber: page.value,
    pageSize: pageSize.value,
    ...searchInfo.value
  })
  if (res.code == 200) {
    tableData.value = res.result.data
    total.value = res.result.total
  }
}
getTableData()

const roleList = ref([])
const fishList = ref([])
onMounted(() => {
  getAuthorityList().then(res => {
    roleList.value = res.result
  })
  fishGroundsList().then(res => {
    fishList.value = res.result
  })
})
const map = ref(null)
const AMaps = ref(null)
function openMap() {
  weizhiDialog.value = true
  initMap()
}
let geocoder = null; // 地图编码转换器
const initMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: "f84f4022a6c10294d1b19ff9b77c31c5",
  };
  AMapLoader.load({
    key: "c1c5d63a1bfa553591a271f0cb521fc1", //此处填入我们注册账号后获取的Key
    version: "2.0", //指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Geocoder"], //需要使用的的插件列表，如比例尺'AMap.Scale'等
  }).then((AMap) => {
    AMaps.value = AMap
    console.log(AMaps.value, 'AMaps.value')
    geocoder = new AMap.Geocoder({
      city: '武汉', // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
    })
    geocoder.getLocation('武汉', function (status, result) {
      console.log(status, result, '3498')
      if (status === "complete" && result.info === "OK") {
        let location = [
          result.geocodes[0].location.lng,
          result.geocodes[0].location.lat,
        ];
        map.value = new AMap.Map("container", {
          zoom: 12, //初始化地图层级
          center: location, //初始化地图中心点
        }); // 展示地图 map
        map.value.on("click", function (e) {
          console.log(e, 'crje')
          var lngLat = e.lnglat;
          form.value.longitude = String(lngLat.lng);
          form.value.latitude = String(lngLat.lat);
          weizhiDialog.value = false
        })
      }
    });
  }).catch(e => {
    console.log(e);
  })
}
const weizhiDialog = ref(false)
const handleClose6 = () => {
  // mapInfo.value = {
  //     address: '',
  //     lng: '',
  //     lat: ''
  // }
  weizhiDialog.value = false
}
const statusChange = (id, val) => {
  pondChangeStatus(id).then(res => {
    ElMessage({
      type: 'success',
      message: '状态修改成功!'
    })
    getTableData()
  })
}
const enterDialog = async () => {
  yyglForm.value.validate(async (valid) => {
    if (valid) {
      form.value.openTime = form.value.time.join(' - ')
      let res
      if (isEdit.value) {
        res = await pondedit(form.value)
      } else {
        res = await pondAdd(form.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}

const delUnit = (row) => {
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await pondDelete(row.id)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const editUnit = async (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑'
  form.value = JSON.parse(JSON.stringify(row))
  console.log(form.value.openTime)
  form.value.time = form.value.openTime.split('-')
  form.value.pondId = form.value.id
  dialogFormVisible.value = true
}

const onSubmit = () => {
  page.value = 1
  getTableData()
}

const onReset = () => {
  page.value = 1
  searchInfo.value = {
    name: '',
    groundsId: ''
  }
  getTableData()
}
const diaoweiDialog = ref(false)
function addDiaoWei() {
  dwVisible.value = true
}
const diaoWeiStatus = ['', '空闲', '使用中', '维修中']
function getStatus(val) {
  return diaoWeiStatus[val]
}
const diaoweiData = ref([])
const dwForm = ref({
  no: '',
  pondId: ''
})
function openDiaoWei(row) {
  dwForm.value.pondId = row.id
  fishSpotList(row.id).then(res => {
    diaoweiData.value = res.result
    diaoweiDialog.value = true
  })
}
const dwVisible = ref(false)
const dwForms = ref(null)
const dialogTitle2 = ref('添加钓位')
function handleClose3() {
  dwForms.value.resetFields()
  dwForm.value = {
    no: '',
    pondId: ''
  }
  dwVisible.value = false
}
function closeDialog2() {
  dwVisible.value = false
}
function handleClose2() {
  diaoweiDialog.value = false
}
const isDwEdit = ref(false)
function enterDialog2() {
  dwForms.value.validate(async (valid) => {
    if (valid) {
      form.value.openTime = form.value.time.join(' - ')
      let res
      if (isDwEdit.value) {
        res = await pondedit(form.value)
      } else {
        res = await fishSpotAdd(dwForm.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        fishSpotList(dwForm.value.pondId).then(res => {
          diaoweiData.value = res.result
        })
      }
      dwForms.value.resetFields()
      dwForm.value.no = ''
      dwVisible.value = false
    }
  })
}
function delDw(row) {
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await fishSpotDelete(row.id)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      fishSpotList(dwForm.value.pondId).then(res => {
        diaoweiData.value = res.result
      })
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}
const statusVisible = ref(false)
const statusForms = ref(null)
const statusForm = ref({
  useStatus: 1,
  spotId: ''
})
function changeStatus(row) {
  console.log(row, 'row')
  statusForm.value.spotId = row.id
  statusForm.value.useStatus = row.useStatus
  statusVisible.value = true
}

function handleClose4() {
  statusVisible.value = false
}
function enterDialog4() {
  spotChangeStatus(statusForm.value).then(res => {
   if(res.code==200){
    ElMessage({
      type: 'success',
      message: '修改成功'
    })
    fishSpotList(dwForm.value.pondId).then(res => {
        diaoweiData.value = res.result
      })
    statusVisible.value = false
   }
  })
}
</script>

<style lang="scss" scoped>
.flex {
  .area {
    flex: 2;
    background-color: #fff;
    margin: 0.5rem 20px 0.5rem 0;
  }

  .unit {
    flex: 4;
  }
}

.ant-alert-info {
  display: flex;
  justify-content: end;
  align-items: center;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  color: #1890ff;
  padding: 5px;

  .anticon {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
}

.pop-content {
  .pop-title {
    font-weight: bold;
    padding-bottom: 4px;
    border-bottom: 1px solid rgba(5, 5, 5, 0.06);
  }

  .el-checkbox-group {
    font-size: 0;
    line-height: 0;
    display: flex;
    flex-wrap: wrap;
  }
}

#container {
  width: 100%;
  height: 100%;
}
</style>
